package com.market.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author luunt
 *
 * @param <T>
 */
public abstract class AbstractJpaDao <T extends DomainObject> implements AbstractDao<T> {
	
	private Class<T> type;
	protected EntityManager em;
	
	@PersistenceContext
	public void setEm(EntityManager em) {
		this.em = em;
	}
	
	public AbstractJpaDao(Class<T> type) {
		super();
		this.type = type;
	}
	
	@Transactional (readOnly=true)
	@Override
	public T find(Long id) {
		if (null == id) {
			return null;
		}
		return em.find(type, id);
	}
	
	@SuppressWarnings("unchecked")
	@Transactional (readOnly=true)
	@Override
	public List<T> findAll() {
		return em.createQuery("select o from " + type.getName() + " o ").getResultList();
	}

	@Transactional (readOnly=true)
	@Override
	public void insert(T entity) {
		em.persist(entity);
	}

	@Transactional (readOnly=true)
	@Override
	public T update(T entity) {
		return em.merge(entity);
	}

	@Transactional (readOnly=true)
	@Override
	public void remove(T entity) {
		em.remove(entity);		
	}

	@Transactional (readOnly=true)
	@Override
	public void remove(Long id) {
		T entity = find(id);
		remove(entity);
	}	
}
